package me.seu.demo.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: 幻冰
 * @Date: 2020/7/23 15:50
 */
public final class FileUtils {

    /**
     * 工具类不允许创建对象和继承
     */
    private FileUtils() {
    }

    /**
     * java文件压缩工具类，传过来的数据流，全部会自动关闭
     *
     * @param targetPath 目标文件夹位置，压缩之后数据的存放位置
     * @param files      可变参数，文件列表
     * @return true：压缩成功；false：压缩失败
     */
    public static boolean compression(String targetPath, File... files) {
        if (files == null || files.length == 0) {
            throw new IllegalArgumentException("compression file list not empty!");
        }
        if (targetPath == null || targetPath.length() == 0 || targetPath.trim().equals("")) {
            throw new IllegalArgumentException("compression file target path not empty!");
        }
        List<File> fileList = new ArrayList<>(10);
        Collections.addAll(fileList, files);
        return compression(targetPath, fileList);
    }

    /**
     * java文件压缩工具类，传过来的数据流，全部会自动关闭
     *
     * @param targetPath 目标文件夹位置，压缩之后数据的存放位置
     * @param files      文件列表
     * @return true：压缩成功；false：压缩失败
     */
    public static boolean compression(String targetPath, List<File> files) {
        if (files == null || files.size() == 0) {
            throw new IllegalArgumentException("compression file list not empty!");
        }
        if (targetPath == null || targetPath.length() == 0 || targetPath.trim().equals("")) {
            throw new IllegalArgumentException("compression file target path not empty!");
        }
        try {
            return compression(new FileOutputStream(targetPath), files);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * java文件压缩工具类，传过来的数据流，全部会自动关闭
     *
     * @param outputStream 压缩文件的输出流，压缩之后的文件输出地址
     * @param files        文件列表
     * @return true：压缩成功；false：压缩失败
     */
    public static boolean compression(OutputStream outputStream, List<File> files) {
        FileInputStream fileInputStream = null;
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, StandardCharsets.UTF_8);
        try {
            for (File file : files) {
                byte[] bufferByte = new byte[1024 * 1024];
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                int len = 0;
                fileInputStream = new FileInputStream(file);
                while ((len = fileInputStream.read(bufferByte)) != -1) {
                    zipOutputStream.write(bufferByte, 0, len);
                }
                zipOutputStream.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                zipOutputStream.close();
                assert fileInputStream != null;
                fileInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * java文件压缩工具类，传过来的数据流，全部会自动关闭
     *
     * @param targetPath           目标文件夹位置，压缩之后数据的存放位置
     * @param stringInputStreamMap 文件名和文件字节的映射关系
     * @return true：压缩成功；false：压缩失败
     */
    public static boolean compression(String targetPath, Map<String, byte[]> stringInputStreamMap) {
        if (targetPath == null || targetPath.length() == 0 || targetPath.trim().equals("")) {
            throw new IllegalArgumentException("compression file target path not empty!");
        }
        if (stringInputStreamMap == null || stringInputStreamMap.size() == 0) {
            throw new IllegalArgumentException("compression stringInputStreamMap list not empty!");
        }
        try {
            return compression(new FileOutputStream(targetPath), stringInputStreamMap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * java文件压缩工具类，传过来的数据流，全部会自动关闭
     *
     * @param outputStream      压缩文件的输出流，压缩之后的文件输出地址
     * @param stringFileByteMap 文件名和文件字节的映射关系
     * @return true：压缩成功；false：压缩失败
     */
    public static boolean compression(OutputStream outputStream, Map<String, byte[]> stringFileByteMap) {
        if (outputStream == null) {
            throw new IllegalArgumentException("compression outputStream not empty!");
        }
        if (stringFileByteMap == null || stringFileByteMap.size() == 0) {
            throw new IllegalArgumentException("compression stringFileByteMap list not empty!");
        }
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, StandardCharsets.UTF_8);
        InputStream inputStream;
        try {
            for (Map.Entry<String, byte[]> stringFileByteEntry : stringFileByteMap.entrySet()) {
                inputStream = new ByteArrayInputStream(stringFileByteEntry.getValue());
                byte[] bufferByte = new byte[1024 * 1024];
                zipOutputStream.putNextEntry(new ZipEntry(stringFileByteEntry.getKey()));
                int len;
                while ((len = inputStream.read(bufferByte)) != -1) {
                    zipOutputStream.write(bufferByte, 0, len);
                }
                inputStream.close();
                zipOutputStream.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                zipOutputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * java文件压缩工具类,
     *
     * @param stringFileByteMap 文件名和文件字节的映射关系
     * @return btye[]：返回值为字节数组
     */
    public static byte[] compression(Map<String, byte[]> stringFileByteMap) throws Exception {
        if (stringFileByteMap == null || stringFileByteMap.size() == 0) {
            throw new IllegalArgumentException("compression stringFileByteMap list not empty!");
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(32);
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, StandardCharsets.UTF_8);
        InputStream inputStream;
        try {
            for (Map.Entry<String, byte[]> stringFileByteEntry : stringFileByteMap.entrySet()) {
                inputStream = new ByteArrayInputStream(stringFileByteEntry.getValue());
                byte[] bufferByte = new byte[1024 * 1024];
                zipOutputStream.putNextEntry(new ZipEntry(stringFileByteEntry.getKey()));
                int len;
                while ((len = inputStream.read(bufferByte)) != -1) {
                    zipOutputStream.write(bufferByte, 0, len);
                }
                inputStream.close();
                zipOutputStream.closeEntry();
            }
        } catch (IOException e) {
            throw new Exception("Service error");
        } finally {
            try {
                zipOutputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outputStream.toByteArray();
    }

}
